package cn.linkai.star.graph.core.interceptor;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

import java.security.Principal;
import java.util.List;

public class WebsocketUserInterceptor implements ChannelInterceptor {
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        //判断当前请求是否建立连接的请求
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor (message, StompHeaderAccessor.class);
        if(accessor!=null && StompCommand.CONNECT.equals (accessor.getCommand ())){
            //从头连接获取clientId
            List<String> clientIds = accessor.getNativeHeader ("clientId");
            System.out.println ("获取到客户端id clientId:"+clientIds);
            //修复逻辑：当clientIds不为null且不为空时才设置用户
            if(clientIds != null && !clientIds.isEmpty()){
                //缓存clientId和通道对应关系
                final String clientId = clientIds.get(0);
                accessor.setUser (() -> clientId);
            }
        }
        return message;
    }
}